package top.lyjwn.ajui.util.store;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import java.io.File;

/**
 * 没有权限限制的持久型键值对存储
 * <p>
 * 注意！高并发使用可能会因排他锁🔒造成异常
 *
 * @author luoyujie
 */
public class LibertyStoreUtil {

    /**
     * 存入键值
     *
     * @param context
     * @param key
     * @param value
     */
    public static void put(Context context, String key, Object value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        File externalFilesDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        File file = new File(externalFilesDir, key);
        String jsonString = jsonObject.toJSONString();
        FileStoreStringUtil.saveStringToFile(file, jsonString);
    }

    /**
     * 读取键值
     *
     * @param context
     * @param key
     * @return
     */
    public static Object get(Context context, String key) {
        File externalFilesDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        File file = new File(externalFilesDir, key);
        String s = FileStoreStringUtil.readStringByFile(file);
        try {
            JSONObject jsonObject = JSONObject.parseObject(s);
            if (jsonObject == null) {
                return null;
            }
            return jsonObject.get(key);
        } catch (com.alibaba.fastjson.JSONException e) {
            Log.e("LibertyStoreUtilFail", s);
        }
        return s;
    }
}
